Imports System.Configuration
Imports System.Web.Mail
Imports System.IO
Imports System.Data.SqlClient

Public Class MailService
    Public Enum eMailType        
        NewPasswordNotification
        CustomerApprovalNotification
    End Enum

    Private Const FromTemplate As String = "#From#"
    Private Const SubjectTemplate As String = "#Subject#"

    Public Class NewPasswordTemplateItems
        Public Const UserFullName As String = "#User#"
        Public Const LoginName As String = "#LoginName#"
        Public Const NewPassword As String = "#Password#"
    End Class

    Public Class CustomerApprovalTemplateItems
        Public Const ChangePasswordLink As String = "#ChangePasswordLink#"
    End Class

    Private m_ModuleName As eMailType
    Protected m_TemplateItems As Hashtable
    Protected m_FromDefault As String
    Protected m_SubjectDefault As String
    Protected m_TemplateFileName As String

    Public Sub New(ByVal ModuleName As eMailType, ByVal TemplateItems As Hashtable, ByVal TemplatePath As String)
        m_ModuleName = ModuleName
        m_TemplateItems = TemplateItems

        Select Case (ModuleName)
            Case eMailType.NewPasswordNotification
                m_FromDefault = ConfigurationSettings.AppSettings("EmailTemplate.NewPasswordNotification.From")
                m_SubjectDefault = ConfigurationSettings.AppSettings("EmailTemplate.NewPasswordNotification.Subject")
                m_TemplateFileName = TemplatePath + ConfigurationSettings.AppSettings("EmailTemplate.NewPasswordNotification.Location")
            Case eMailType.CustomerApprovalNotification
                m_FromDefault = ConfigurationSettings.AppSettings("EmailTemplate.CustomerApprovalNotification.From")
                m_SubjectDefault = ConfigurationSettings.AppSettings("EmailTemplate.CustomerApprovalNotification.Subject")
                m_TemplateFileName = TemplatePath + ConfigurationSettings.AppSettings("EmailTemplate.CustomerApprovalNotification.Location")
        End Select
    End Sub

    Protected Function LoadTemplate() As MailMessage
        Dim result As New MailMessage
        Dim fs As FileStream
        Try
            fs = New FileStream(m_TemplateFileName, FileMode.Open, FileAccess.Read)
        Catch ex As Exception
            Throw New ApplicationException("Failed to open template !", ex)
        End Try
        Dim r As StreamReader = New StreamReader(fs)

        result.Body = r.ReadToEnd()
        result.From = m_FromDefault
        result.Subject = m_SubjectDefault
        result.BodyFormat = MailFormat.Html
        r.Close()

        Return result
    End Function

    Protected Sub TransformMailContent(ByRef Content As String)
        Dim key As String
        For Each key In m_TemplateItems.Keys
            Content = Content.Replace(key, CStr(m_TemplateItems(key)))
        Next
    End Sub

    Public Overloads Sub Send(ByVal msg As MailMessage)
        If (msg.To = "") Then
            Return
        End If
        If (msg.From = "") Then
            msg.From = m_FromDefault
        End If
        If (msg.Subject = "") Then
            msg.Subject = m_SubjectDefault
        End If

        m_TemplateItems.Add(FromTemplate, msg.From)
        m_TemplateItems.Add(SubjectTemplate, msg.Subject)

        ' Transform mail content
        TransformMailContent(msg.Body)

        ' Send mail
        Try
            SmtpMail.SmtpServer = ConfigurationSettings.AppSettings("MIMS_WRS.SMTPServer")
            SmtpMail.Send(msg)
        Catch ex As Exception
            Throw New ApplicationException("Failed to send email !", ex)
        End Try

    End Sub

    Public Overloads Sub Send(ByVal ToAddress() As String, Optional ByVal FromAddress As String = "", Optional ByVal Subject As String = "")
        Dim i As Integer
        For i = 0 To ToAddress.Length - 1
            Me.Send(ToAddress(i), FromAddress, Subject)
        Next
    End Sub

    Public Overloads Sub Send(ByVal ToMailAddr As String, Optional ByVal FromMailAddr As String = "", Optional ByVal Subject As String = "")
        If (ToMailAddr = "") Then
            Return
        End If

        ' Construct msg to send
        Dim msg As MailMessage = LoadTemplate()
        msg.To = ToMailAddr
        If (FromMailAddr <> "") Then
            msg.From = FromMailAddr
        End If
        If (Subject <> "") Then
            msg.Subject = Subject
        End If

        ' Add some more template value
        m_TemplateItems.Add(FromTemplate, msg.From)
        m_TemplateItems.Add(SubjectTemplate, msg.Subject)

        ' Replace template items in msg body by template values
        TransformMailContent(msg.Body)

        ' Send mail
        Try
            SmtpMail.SmtpServer = ConfigurationSettings.AppSettings("MIMS_WRS.SMTPServer")
            SmtpMail.Send(msg)
        Catch ex As Exception
            Throw New ApplicationException("Failed to send email !", ex)
        End Try
    End Sub

    Public Shared Sub UploadTemplate(ByVal eTemplateType As eMailType, ByVal file As System.Web.UI.HtmlControls.HtmlInputFile, ByVal TemplatePath As String)
        Dim buf() As Byte
        GetFileContentFrom(file, buf)

        If (file.PostedFile Is Nothing) Then
            Return
        End If

        Dim TemplateFileName As String
        Select Case eTemplateType
            'Case eMailType.Project
            '    TemplateFileName = TemplatePath + ConfigurationSettings.AppSettings("RIM.PDA.EmailTemplate.Project.Body")
            'Case eMailType.Task
            '    TemplateFileName = TemplatePath + ConfigurationSettings.AppSettings("RIM.PDA.EmailTemplate.Task.Body")
        End Select
        file.PostedFile.SaveAs(TemplateFileName)
    End Sub

    Protected Shared Function GetFileContentFrom(ByVal file As System.Web.UI.HtmlControls.HtmlInputFile, ByVal buf As Byte()) As Long
        With file
            If Not .PostedFile Is Nothing Then
                With .PostedFile
                    Dim numBytesToRead As Integer = CInt(.InputStream.Length)
                    Dim numBytesRead As Integer = 0
                    While numBytesToRead > 0
                        ' Read may return anything from 0 to numBytesToRead.
                        Dim n As Integer = .InputStream.Read(buf, numBytesRead, numBytesToRead)
                        If n = 0 Then ' We're at EOF
                            Exit While
                        End If
                        numBytesRead += n
                        numBytesToRead -= n
                    End While
                    .InputStream.Close()
                    Return numBytesRead
                End With
            End If
        End With
        Return 0
    End Function

End Class
